package com.codeyang.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codeyang.domain.SmsLog;
import com.codeyang.mapper.SmsLogMapper;
import com.codeyang.model.AliSmsModel;
import com.codeyang.model.WxMsgModel;
import com.codeyang.service.SmsLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 描述:
 *
 * @author CodeYang_Site
 * @version 2021/5/30 10:07
 */
@Slf4j
@Service
public class SmsLogServiceImpl extends ServiceImpl<SmsLogMapper, SmsLog> implements SmsLogService {

    @Autowired
    private SmsLogMapper smsLogMapper;


    /**
     * 记录 阿里短信发送记录到DB
     *
     * @param userId
     * @param aliSmsModel
     * @param sendSmsResponse
     */
    @Override
    public void saveAliSms(String userId, AliSmsModel aliSmsModel, SendSmsResponse sendSmsResponse) {
        // 获取验证码值
        String code = JSON.parseObject(aliSmsModel.getTemplateParam()).getString("code");
        SmsLog smsLog = SmsLog.builder()
                .userId(userId)
                .content("阿里短信验证码为:" + code)
                .mobileCode(code)
                .recDate(new Date())
                .type(2)
                .status(sendSmsResponse.getCode().equalsIgnoreCase("OK") ? 1 : 0)
                .responseCode(sendSmsResponse.getCode())
                .build();
        smsLogMapper.insert(smsLog);
    }

    /**
     * 记录微信发送消息
     *
     * @param wxMsgModel
     * @param result
     */
    @Override
    public void saveWxMsg(WxMsgModel wxMsgModel, ResponseEntity<String> result) {
        //直接在这里组装 微信发送的是否成功的code值0 才是真正的成功
        String body = result.getBody();
        JSONObject jsonObject = JSON.parseObject(body);
        String errcode = jsonObject.getString("errcode");
        SmsLog smsLog = SmsLog.builder()
                .userId(wxMsgModel.getToUser())
                .recDate(new Date())
                .content("微信消息")
                .type(2)
                .status(errcode.equals("0") ? 1 : 0)
                .responseCode(result.getStatusCode().toString())
                .build();
        smsLogMapper.insert(smsLog);
    }
}
